//
//  BoxCostHeadView.m
//  XLDoctor
//
//  Created by longma on 2018/10/8.
//  Copyright © 2018年 XLH. All rights reserved.
//

#import "MJConfirmLoadingView.h"

@interface MJConfirmLoadingView ()

@property (nonatomic,strong) NSTimer *countdownTimer;
@property (nonatomic,assign) NSInteger remainingTime;

@end

@implementation MJConfirmLoadingView

- (void)awakeFromNib{
    [super  awakeFromNib];
 
    self.loadingView.contentView.backgroundColor = UIColor.mj_appColor;
    [self.loadingView mj_cornerRadius:self.mj_height/2];
    
    //
    self.countdownButton.mj_enabled = false;

}

- (void)layoutSubviews{
    [super layoutSubviews];
     
}

- (void)startCountdown {
    self.remainingTime = 180;//180 10
    [self.countdownTimer setFireDate:[NSDate distantPast]]; //开启
}
- (void)updateTime{

    if(self.remainingTime > 0){
        [self.countdownButton setTitle:[NSString stringWithFormat:@"%@（%ld）s",MJUILocalizedString(@"Log in"),self.remainingTime] forState:0];
        self.countdownButton.hidden = false;
        self.continueButton.hidden = true;
        
    }else{
        self.countdownButton.hidden = true;
        [self.countdownTimer invalidate];
        self.countdownTimer = nil;
        self.continueButton.hidden = false;

    }
    
    self.remainingTime--;
}

- (void)didMoveToSuperview {
    
    MJWeakSelf
    UIViewController *controller = [UIViewController mj_topViewController];
    if(controller){

        //在我将要dealloc的时候结束通知监听的信号
        [controller.rac_willDeallocSignal subscribeCompleted:^{
            [weakSelf.countdownTimer invalidate];
            weakSelf.countdownTimer = nil;
            weakSelf.countdownButton.hidden = true;
            weakSelf.continueButton.hidden = false;
        }];
        [[controller rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(RACTuple * _Nullable x) {

           

        }];
    }

}

- (void)setEnabled:(BOOL)enabled {
    self.continueButton.mj_enabled = enabled;
}

- (IBAction)handleContinueButtonClick:(UIButton *)sender {
    [self.loadingView startAnimation];
    
    if(self.handleContinueBlock)
        self.handleContinueBlock();
    
}
- (NSTimer *)countdownTimer
{
    if (!_countdownTimer) {
        _countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                            target:self
                                                          selector:@selector(updateTime)
                                                          userInfo:nil
                                                           repeats:YES];
        
        [[NSRunLoop mainRunLoop] addTimer:_countdownTimer forMode:NSRunLoopCommonModes];

    }
    return _countdownTimer;
}
@end
